// api/documentsApi.ts

/**
 * 文档管理 API 封装
 * 对应后端 api/endpoints/documents/documents.py，用于管理已索引文档的信息。
 */

import { initializeApiConfig } from './config';
const API_BASE = initializeApiConfig(); 

interface ErrorDetail {
  detail: string;
}

// 假设 handleResponse 函数存在
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    let errorDetail: ErrorDetail = { detail: '未知 API 错误' };
    try {
      errorDetail = await response.json();
    } catch (e) {
      const text = await response.text();
      errorDetail.detail = response.statusText + ': ' + text.substring(0, 100) + '...';
    }
    throw new Error(errorDetail.detail);
  }
  // 仅在响应有内容时解析JSON
  if (response.status !== 204 && response.headers.get('content-length') !== '0') {
      return response.json();
  }
  return {} as T; // 返回空对象以满足 Promise<T>
}
// -------------------------------------------------------------------

// --- 类型定义 ---

export interface DocumentInfo {
  file_hash: string;
  file_name: string;
}

export interface DocumentMetadata {
    file_name: string;
    page_label: string;
}

export interface DocumentChunk {
    text: string; // 可能是截断的文本
    metadata: DocumentMetadata;
}

// -------------------------------------------------------------------
// --- API 方法定义 ---
// -------------------------------------------------------------------

/**
 * 列出所有已上传的文档
 * GET /api/v1/documents/documents
 * @param keyword 关键词过滤文件名
 */
export const listDocuments = async (keyword?: string): Promise<DocumentInfo[]> => {
  const params = new URLSearchParams();
  if (keyword) params.append('keyword', keyword);

  const response = await fetch(`${API_BASE}/documents/documents?${params.toString()}`);
  return handleResponse(response);
};

/**
 * 根据文件哈希值获取文档的原始文本和元数据（按页/块）
 * GET /api/v1/documents/doc-metadata
 * @param fileHash 目标文档的哈希值
 */
export const getDocumentMetadata = async (fileHash: string): Promise<DocumentChunk[]> => {
  const params = new URLSearchParams({
    file_hash: fileHash,
  });

  const response = await fetch(`${API_BASE}/documents/doc-metadata?${params.toString()}`);
  return handleResponse(response);
};